<?php
// Turn off all error reporting
error_reporting(0);
require('../includes/mysql.connect.php');

/**
 * Display image form database
 *
 * Retrive an image from mysql database if image id is provided.
 *
 * @example to display a image with image id 1, place <img src="image.php?id=1" > in your html file.
 *
 * @author Md. Rayhan Chowdhury
 * @copyright www.raynux.com
 * @license LGPL
 */

// verify request id.
if (empty($_GET['id'])) {
        echo 'A valid image file id is required to display the image file.';
        exit;
}

$imageId = $_GET['id'];

//connect to mysql database

if ($mysqli) {
        
        $content = mysqli_real_escape_string($mysqli, $content);
        
        
        switch ($_GET['size']) {
            case "thumb":
                $size = 'thumb';
                break;
            case "resized":
                $size = 'resized';
                break;
            default:
                $size = 'content';
                break;
        }
        
        $sql = "SELECT type, ".$size." as 'content',name,date_added,size FROM images where image_id = '{$imageId}' ORDER BY `date_added` DESC LIMIT 0,1";
        //print($sql);

        if ($rs = mysqli_query($mysqli, $sql)) {
                $imageData = mysqli_fetch_array($rs, MYSQLI_ASSOC);
                mysqli_free_result($rs);
        } else {
                echo "Error: Could not get data from mysql database. Please try again.";
        }
        //close mysqli connection
        mysqli_close($mysqli);

} else {
        echo "Error: Could not connect to mysql database. Please try again.";
}
//No matter if we have an image stored or not, we want the user to cache the result.
header('Pragma: public');
header('Cache-Control: max-age=172800');  // 172800seconds is 2 days.
header('Expires: '. gmdate('D, d M Y H:i:s \G\M\T', time() + 86400));
$etag = md5($imageData['name'].$imageData['size'].$imageData['date_added']);
header("Last-Modified: " . gmdate("D, d M Y H:i:s", strtotime($imageData['date_added'])) . " GMT");
header('ETag: "'.$etag.'"');
if (!empty($imageData)) {
        // show the image.
        header("Content-type: {$imageData['type']}");

        
        echo $imageData['content'];
}
else {
    	print file_get_contents('NoImageAvailable.png');
}
?>